package si.yun.web;

import com.mysql.cj.jdbc.DatabaseMetaData;
import com.mysql.cj.util.StringUtils;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.UserAgent;
import eu.bitwalker.useragentutils.Version;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import si.yun.service.SyLoginLogSelService;
import si.yun.service.SyLoginService;
import si.yun.utils.JsonData;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName: 用户登录Web层
 * @Description: TODO
 * @Author: 柴秋生
 * @Date 2021/7/28 19:30
 */
@Controller
@RequestMapping("/login")
@PropertySource({"classpath:application.properties"})
public class SyLoginController {
    @Autowired
    private SyLoginService syUserService;
    @Autowired
    private SyLoginLogSelService syLoginLogSelService;
    @Value("${fdfs.tracker-list}")
    private String serverName;

    @Value("${spring.servlet.multipart.max-file-size}")
    private String maxSize;

    @Value("${fdfs.connect-timeout}")
    private String connectTimeOut;

    @Value("${fdfs.so-timeout}")
    private String readTimeOut;

    @Value("${spring.datasource.url}")
    private String url;

    @Value("${spring.datasource.username}")
    private String userName;

    @Value("${spring.datasource.password}")
    private String password;
  
    /**
     * 查询登录日志
     * @Author : 柴秋生
     * @Date : 2021/8/15 10:01
     * @Param : []
     * @Return : java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     */
    @ResponseBody
    @RequestMapping("/selLoginLogs")
    public JsonData selLoginLogs(String mid){
        List<Map<String,Object>> selLoginLogs=syLoginLogSelService.selLoginLogs(mid);
        return selLoginLogs!=null? JsonData.buildSuccess(selLoginLogs): JsonData.buildError("服务器端错误");
    }

  /**
     * @return si.yun.entity.PerCount
     * @Description 跳转错误页面
     * @Date 2021/7/29 14:37
     **/
    @RequestMapping("/toError")
    public String error(){
        return "redirect:/public/index/error.html";
    }

 /**
     * @return si.yun.entity.PerCount
     * @Description 跳转登陆界面
     * @Date 2021/7/29 14:37
     **/
    @RequestMapping("/index")
    public String index(){
        return "index";
    }
  /**
     * @return si.yun.entity.PerCount
     * @Description 跳转登录成功后的页面
     * @Date 2021/7/29 14:37
     **/
    @RequestMapping("/login")
    public String login(){
        return "login/SyLogin.html";
    }
	
    /**
     * @return si.yun.entity.PerCount
     * @Description 跳转微圈管理页面
     * @Date 2021/7/29 14:37
     **/
    @RequestMapping("/AdministrationForum")
    public String AdministrationForum(){
        return "/teacher/AdministrationForum.html";
    }

    /**
     * @return si.yun.entity.PerCount
     * @Description 跳转系统首页
     * @Date 2021/7/29 14:37
     **/
    @RequestMapping("/System")
    public String System(){
        return "/public/System.html";
    }

    /**
     * @return si.yun.entity.PerCount
     * @Description 账户设置
     * @Date 2021/7/29 14:37
     **/
    @RequestMapping("/Account")
    public String Account(){
        return "/public/Account.html";
    }

    /**
     * @return si.yun.entity.PerCount
     * @Description 系统信息
     * @Date 2021/7/29 14:37
     **/
    @RequestMapping("/SystemInformation")
    public String SystemInformation(){
        return "/public/SystemInformation.html";
    }

    /**
     * @return si.yun.entity.PerCount
     * @Description 登录日志
     * @Date 2021/7/29 14:37
     **/
    @RequestMapping("/LoginLog")
    public String LoginLog(){
        return "/public/LoginLog.html";
    }






    @ResponseBody
    @GetMapping("/selSystemInfo")
    public JsonData selSystemInfo(HttpServletRequest request){
        Map<String,Object> map = new HashMap<>();
        //获取服务器端口号
        int serverPort = request.getServerPort();
        //获取服务器IP
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 ||"unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 ||"unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 ||"unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        //获取当前运行环境信息
        String os = System.getProperty("os.name");//操作系统
        String version = System.getProperty("java.version");//Java 运行时环境版本
        String vendor = System.getProperty("java.vendor");//Java 运行时环境供应商
        String url = System.getProperty("java.vendor.url");//Java 供应商的 URL
        String JavaVen = version+","+vendor+","+url;
        //获取浏览器信息
        Browser browser = UserAgent.parseUserAgentString(request.getHeader("User-Agent")).getBrowser();
        //获取浏览器版本号
        Version ieVersion = browser.getVersion(request.getHeader("User-Agent"));
        String ieName = browser.getName();
        String ieVersionInfo = ieVersion.getVersion();
        //获取mysql版本号
        String databaseMajorVersion = getDatabaseMajorVersion();
        map.put("databaseMajorVersion",databaseMajorVersion);
        //服务器名称
        map.put("serverName",serverName);
        //端口号
        map.put("serverPort",serverPort);
        //服务器地址
        map.put("ip",ip);
        //操作系统
        map.put("os",os);
        //java运行环境
        map.put("javaVen",JavaVen);
        //IE名称
        map.put("ieName",ieName);
        //IE版本
        map.put("ieVersionInfo",ieVersionInfo);
        //连接超时时间
        map.put("connectTimeOut",connectTimeOut+"ms");
        //读取超时时间
        map.put("readTimeOut",readTimeOut+"ms");
        //上传大小限制
        map.put("maxSize",maxSize);
       return map!=null? JsonData.buildSuccess(map): JsonData.buildError("服务器端错误");
    }

    /**
     * 通过Jdbc的方式获取数据库的版本
     * @return
     */
    private String getDatabaseMajorVersion() {
        String version = null;
        try {
            // 加载驱动程序
            // 下面的代码为加载JDBD-ODBC驱动程序
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 建立连接
            // 用适当的驱动程序连接到DBMS，看下面的代码[自行修改您所连接的数据库相关信息]：
            // 用url创建连接
            Connection con = DriverManager.getConnection(url, userName, password);
            // 获取数据库的信息
            DatabaseMetaData dbMetaData = (DatabaseMetaData) con.getMetaData();
            // 返回数据库的版本号。
            version = dbMetaData.getDatabaseProductVersion();
            // 关闭连接
            con.close();
        } catch (Exception e) {
            // 输出异常信息
            System.err.println("SQLException :" + e.getMessage());
            e.printStackTrace();
        }
        return version;
    }
}
